﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Newtonsoft.Json.Linq;

namespace NGM.MicrosoftConnect {
    public class MicrosoftConnectClient {
        private readonly string _accessToken;

        public MicrosoftConnectClient(string accessToken) {
            _accessToken = accessToken;
        }

        public dynamic Get(string url) {
            var builder = new MicrosoftConnectWebRequestBuilder(_accessToken, url);
            var webRequest = builder.Build();

            using (var webResponse = webRequest.GetResponse())
            using (var responseStream = webResponse.GetResponseStream()) {
                if (responseStream == null)
                    return null;

                using (var streamReader = new StreamReader(responseStream, Encoding.UTF8)) {
                    return JObject.Parse(streamReader.ReadToEnd());
                }
            }
        }

        public dynamic Post(string url, IDictionary<string, string> parameters) {
            var builder = new MicrosoftConnectWebRequestBuilder(_accessToken, url);
            builder.WithWebRequestType(System.Net.WebRequestMethods.Http.Post);
            builder.WithContentType(MicrosoftConnectConstants.ApplicationJsonContentType);
            var webRequest = builder.Build();

            using (StreamWriter writer = new StreamWriter(webRequest.GetRequestStream())) {
                foreach (var parameter in parameters) {
                    writer.Write("{0}:{1}", parameter.Key, parameter.Value);
                }
            }

            using (var webResponse = webRequest.GetResponse())
            using (var responseStream = webResponse.GetResponseStream()) {
                if (responseStream == null)
                    return null;

                using (var streamReader = new StreamReader(responseStream, Encoding.UTF8)) {
                    return JObject.Parse(streamReader.ReadToEnd());
                }
            }
        }
    }
}